<script setup>
import { Popover, Icon } from 'vant'
import { ref, onMounted, computed } from 'vue'
import ChangeAmount from '@/pages/contract/components/changeAmount.vue'
import FlowDetail from '@/pages/contract/components/flowDetail.vue'
import PreviewFile from '@/components/previewFile/index.vue'
import { useRoute, useRouter } from 'vue-router'
import Toast from '@/components/toast/index.js'
import { storeToRefs } from 'pinia'
import { enumStore } from '@/store/enum'
import commonModel from '@/http/modules/common.js'
import Utility from '@/utils/utility'
const enum_store = enumStore()
const { enumDslInfo } = storeToRefs(enum_store)
const router = useRouter()
const route = useRoute()
const contractDetail = ref({
  contractInfo: {},
  shipInfo: {},
  goodsList: [],
  recordList: [],
})
const flowList = ref([])
const hasMore = ref(false)
const RefChangeAmount = ref()
async function getContractDetail() {
  try {
    commonModel
      .gatewayApi({
        service: 'cb_trade_contract_detail',
        bizContent: {
          contractOrderNo: route.params.id,
        },
        version: '1.0.0',
      })
      .then((result) => {
        if (result) {
          contractDetail.value = result
          // 已关联入款流水 展示更换接口来源
          if (result.recordList && result.recordList.totalCount > 2) {
            hasMore.value = true
            flowList.value = result.recordList.slice(0, 2)
          } else {
            flowList.value = result.recordList || []
          }
        }
      })
  } catch (e) {
    console.log(e)
  }
}
// const getFlowList = () => {
//   commonModel
//     .gatewayApi({
//       service: 'cb_trade_incoming_page',
//       bizContent: {
//         pageNo: 1,
//         pageSize: 10,
//         contractOrderNo: route.params.id,
//       },
//       version: '1.0.0',
//     })
//     .then((result) => {
//       if (result) {
//         if (result.totalCount > 2) {
//           hasMore.value = true
//           flowList.value = result.dataList.slice(0, 2)
//         } else {
//           flowList.value = result.dataList || []
//         }
//       }
//     })
// }
// 待关联入帐流水
const isRunning = computed(() => {
  return 'Initial'.includes(contractDetail.value.contractStatus)
})
// 待跟进
const isWait = computed(() => {
  return `Returned`.includes(contractDetail.value.contractStatus)
})
// 草稿订单
const isDome = computed(() => {
  return `Draft`.includes(contractDetail.value.contractStatus)
})
// 收款中
const isEntering = computed(() => {
  return `Pending,Risking,Approved`.includes(
    contractDetail.value.contractStatus
  )
})
// 是否是报关单
const isBgd = computed(() => {
  return (
    contractDetail.value.contractInfo &&
    contractDetail.value.contractInfo.declType === 'Y'
  )
})

const isCollectionIng = computed(() => {
  return `Pending,Risking,Approved`.includes(
    contractDetail.value.contractStatus
  )
})
// 未添加关闭合同的接口
function handleClose() {
  Toast.open({
    type: 'none',
    title: '确定要关闭该合同吗？',
    showClose: false,
    confirmFun: () => {
      commonModel
        .gatewayApi({
          service: 'cb_trade_conteact_close',
          bizContent: {
            contractOrderNo: route.params.id,
          },
          version: '1.0.0',
        })
        .then(() => {
          router.go(-1)
          Toast.close()
        })
    },
  })
}
// 未添加收款完成合同的接口
function handleDone() {
  Toast.open({
    type: 'none',
    title: '确定要对该合同做收款完成吗？',
    showClose: false,
    confirmFun: () => {
      commonModel
        .gatewayApi({
          service: 'cb_trade_conteact_complete',
          bizContent: {
            contractOrderNo: route.params.id,
          },
          version: '1.0.0',
        })
        .then(() => {
          router.go(-1)
          Toast.close()
        })
    },
  })
}
function handleEdit() {
  router.push(`/contract/create?id=${contractDetail.value.contractOrderNo}`)
}
function handleLogisticsEdit() {
  router.push(
    `/contract/create?id=${contractDetail.value.contractOrderNo}&step=2`
  )
}
function handleChangAmountClick() {
  RefChangeAmount.value.show = true
}
onMounted(() => {
  // getFlowList()
  getContractDetail()
})
</script>

<template>
  <div class="contract__detail">
    <div class="detail__card amount__box">
      <div class="amount__top">
        <div class="amount__top-left">
          <div class="amount__title">
            <span>合同金额</span>
            <div
              v-if="!isBgd && isCollectionIng"
              class="amount__top-right"
              @click="handleChangAmountClick"
            >
              变更金额
            </div>
          </div>
          <div class="amount__count">
            {{
              $filters.formatMoney(contractDetail.contractInfo.totalOrderAmount)
            }}
            <span class="unit"
              >{{ contractDetail.contractInfo.currency
              }}{{
                Utility.getLabelByValue(
                  enumDslInfo.CurrencyType,
                  contractDetail.contractInfo.currency
                )
              }}</span
            >
          </div>
        </div>
      </div>
      <div class="amount__bottom">
        <div class="amount__bottom-left">
          <div class="left__row">
            <div class="row__label">创建时间</div>
            <div class="row__value">{{ contractDetail.gmtCreate }}</div>
            <div class="status">
              {{
                contractDetail.shipInfo.whetherShip === 'Y'
                  ? '已发货'
                  : '未发货'
              }}
            </div>
          </div>
          <div class="left__row">
            <div class="row__label">合同编号</div>
            <div class="row__value">
              {{ contractDetail.contractInfo.contractNo }}
            </div>
            <div
              class="status"
              :style="{
                color: ['Completed', 'Closed'].includes(
                  contractDetail.contractStatus
                )
                  ? '#999'
                  : '#FAA64E',
              }"
            >
              {{
                Utility.getLabelByValue(
                  enumDslInfo.ContractOrderStatus,
                  contractDetail.contractStatus
                )
              }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 更换字段 -->
    <flow-detail
      :hasMore="hasMore"
      :flowList="flowList"
      v-if="contractDetail.contractInfo.contractNo"
      :contract-detail="contractDetail"
    />
    <div class="detail__card">
      <div class="detail__card-title">申请结汇</div>
      <div class="detail__card-row">
        <div class="row__label">是否结汇</div>
        <div class="row__value">
          <Popover class="tips__popover">
            <div class="tips__box-popover">
              <p>
                根据监管要求，人民币结汇时，将贸易合同订单材料作为结汇依据；
              </p>
              <p>
                *申报结汇:
                由境内合作银行和持牌支付机构提供境内合规入账服务，代您提交申报结汇材料.
              </p>
            </div>
            <template #reference>
              是<Icon name="warning" color="#ccc"></Icon>
            </template>
          </Popover>
        </div>
      </div>
    </div>
    <div class="detail__card">
      <div class="detail__card-title">申请模式</div>
      <div class="detail__card-row">
        <div class="row__label">申报模式</div>
        <div class="row__value">{{ isBgd ? '报关单' : '非报关单' }}</div>
      </div>
    </div>
    <div class="detail__card">
      <div class="detail__card-title">合同订单信息</div>
      <div class="detail__card-row">
        <div class="row__label">贸易国家/地区</div>
        <div class="row__value">
          {{
            Utility.getTargetByValue(
              enumDslInfo.Nationality,
              contractDetail.contractInfo.region
            ).name
          }}
        </div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">买家英文名称</div>
        <div class="row__value">
          {{ contractDetail.contractInfo.buyerName }}
        </div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">订单总金额</div>
        <div class="row__value">
          {{
            $filters.formatMoney(contractDetail.contractInfo.totalOrderAmount)
          }}
        </div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">币种</div>
        <div class="row__value">{{ contractDetail.contractInfo.currency }}</div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">付款方式</div>
        <div class="row__value">
          {{
            contractDetail.contractInfo.payType === '00'
              ? '全额预付'
              : '预付+尾款'
          }}
        </div>
      </div>
      <template v-if="contractDetail.contractInfo.payType === '01'">
        <div class="detail__card-row">
          <div class="row__label">预付款金额</div>
          <div class="row__value">
            {{ $filters.formatMoney(contractDetail.contractInfo.prepayAmount) }}
          </div>
        </div>
        <div class="detail__card-row">
          <div class="row__label">尾款金额</div>
          <div class="row__value">
            {{
              $filters.formatMoney(contractDetail.contractInfo.balanceAmount)
            }}
          </div>
        </div>
      </template>
      <div class="detail__card-row">
        <div class="row__label">合同</div>
        <div class="row__value">
          <preview-file
            :file-url="contractDetail.contractInfo.contractUrls"
            :file-name="contractDetail.contractInfo.contractUrls"
          />
        </div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">CI/PI</div>
        <div class="row__value">
          <preview-file
            :file-url="contractDetail.contractInfo.ciPiUrls"
            :file-name="contractDetail.contractInfo.ciPiUrls"
          />
        </div>
      </div>
    </div>
    <div
      v-show="contractDetail.goodsList"
      v-for="(item, index) in contractDetail.goodsList"
      :key="index"
      class="detail__card"
    >
      <div class="detail__card-title">商品信息</div>
      <template v-if="index === 0">
        <div class="detail__card-row">
          <div class="row__label">商品/店铺网址</div>
          <div class="row__value">{{ contractDetail.goodsUrl }}</div>
        </div>
        <div class="detail__card-row">
          <div class="row__label">商品类目</div>
          <div class="row__value">
            {{
              Utility.getTargetByValue(
                enumDslInfo.GoodsCategoryEnum,
                contractDetail.goodsCategory
              ).name
            }}
          </div>
        </div>
      </template>
      <div class="detail__card-row">
        <div class="row__label">商品英文名称</div>
        <div class="row__value">{{ item.goodsEnName }}</div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">商品中文名称</div>
        <div class="row__value">{{ item.goodsCnName }}</div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">商品数量</div>
        <div class="row__value">{{ item.goodsQty }}</div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">商品单位</div>
        <div class="row__value">{{ item.goodsUnit }}</div>
      </div>
      <div class="detail__card-row">
        <div class="row__label">商品单价</div>
        <div class="row__value">
          {{ $filters.formatMoney(item.goodsUnitPrice) }}
        </div>
      </div>
    </div>
    <div class="detail__card">
      <div class="detail__card-title">物流信息</div>
      <!--   报关单   -->
      <template v-if="isBgd">
        <div class="detail__card-row">
          <div class="row__label">报关单号</div>
          <div class="row__value">
            {{ contractDetail.shipInfo.declVoucherNo }}
          </div>
        </div>
        <div class="detail__card-row">
          <div class="row__label">申报日期</div>
          <div class="row__value">
            {{ contractDetail.shipInfo.declTime }}
          </div>
        </div>
        <div class="detail__card-row">
          <div class="row__label">成交方式</div>
          <div class="row__value">
            {{
              Utility.getTargetByValue(
                enumDslInfo.DealType,
                contractDetail.shipInfo.dealType
              ).name
            }}
          </div>
        </div>
        <div class="detail__card-row">
          <div class="row__label">报关单文件</div>
          <div class="row__value">
            <preview-file
              :file-url="contractDetail.shipInfo.declVoucherUrls"
              :file-name="contractDetail.shipInfo.declVoucherUrls"
            />
          </div>
        </div>
      </template>
      <template v-else>
        <div class="detail__card-row">
          <div class="row__label">是否发货</div>
          <div class="row__value">
            {{ contractDetail.shipInfo.whetherShip === 'Y' ? '是' : '否' }}
          </div>
        </div>
        <template v-if="contractDetail.shipInfo.whetherShip === 'Y'">
          <div class="detail__card-row">
            <div class="row__label">发货模式</div>
            <div class="row__value">
              {{
                Utility.getTargetByValue(
                  enumDslInfo.ShipMode,
                  contractDetail.shipInfo.shipMode
                ).name
              }}
            </div>
          </div>
          <div
            v-if="contractDetail.shipInfo.shipMode === '01'"
            class="detail__card-row"
          >
            <div class="row__label">货代名称</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.ffCopName }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">实际发货日期</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.shipTime }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">物流公司名称</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.logisticsCopName }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">实际物流方式</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.logisticsType }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">出境物流单号</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.outLogisticsBillNo }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">成交方式</div>
            <div class="row__value">
              {{
                Utility.getTargetByValue(
                  enumDslInfo.DealType,
                  contractDetail.shipInfo.dealType
                ).name
              }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">发货凭证</div>
            <div class="row__value">
              <preview-file
                :file-url="contractDetail.shipInfo.shopVoucherNo"
                :file-name="contractDetail.shipInfo.shopVoucherNo"
              />
            </div>
          </div>
        </template>
        <template v-else>
          <div class="detail__card-row">
            <div class="row__label">新/老买家</div>
            <div class="row__value">
              {{
                contractDetail.shipInfo.buyerType === '00' ? '新买家' : '老买家'
              }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">预计发货日期</div>
            <div class="row__value">
              {{ contractDetail.shipInfo.gmtEstShipTime }}
            </div>
          </div>
          <div class="detail__card-row">
            <div class="row__label">成交方式</div>
            <div class="row__value">
              {{
                Utility.getTargetByValue(
                  enumDslInfo.DealType,
                  contractDetail.shipInfo.dealType
                ).name
              }}
            </div>
          </div>
          <template v-if="contractDetail.shipInfo.buyerType === '00'">
            <div class="detail__card-row">
              <div class="row__label">询盘下单沟通记录</div>
              <div class="row__value">
                <preview-file
                  :file-url="contractDetail.shipInfo.askOrderUrls"
                  :file-name="contractDetail.shipInfo.askOrderUrls"
                />
              </div>
            </div>
            <div class="detail__card-row">
              <div class="row__label">货运安排沟通记录</div>
              <div class="row__value">
                <preview-file
                  :file-url="contractDetail.shipInfo.shipLogisticsUrls"
                  :file-name="contractDetail.shipInfo.shipLogisticsUrls"
                />
              </div>
            </div>
          </template>
          <div v-else class="detail__card-row">
            <div class="row__label">
              与该买家最近一笔交易的报关单或出境物流凭证
            </div>
            <div class="row__value">
              <preview-file
                :file-url="contractDetail.shipInfo.customsVoucherUrls"
                :file-name="contractDetail.shipInfo.customsVoucherUrls"
              />
            </div>
          </div>
        </template>
      </template>
    </div>
    <div class="contract__tool">
      <div v-if="isRunning || isWait" class="tool__btn" @click="handleClose">
        关闭
      </div>
      <div
        v-if="isDome || isRunning || isWait"
        class="tool__btn"
        @click="handleEdit"
      >
        编辑订单
      </div>
      <div
        v-if="!isBgd && isEntering"
        class="tool__btn"
        @click="handleLogisticsEdit"
      >
        变更发货信息
      </div>
      <div
        v-if="
          !contractDetail.lockedAmount &&
          contractDetail.receivedAmount &&
          contractDetail.shipInfo.whetherShip === 'Y' &&
          contractDetail.contractStatus !== 'Completed'
        "
        class="tool__btn"
        @click="handleDone"
      >
        收款完成
      </div>
    </div>
    <change-amount
      ref="RefChangeAmount"
      :contract-detail="contractDetail"
      @refresh="getContractDetail"
    />
  </div>
</template>

<style lang="scss" scoped>
.contract__detail {
  padding: 10px 12px 40px 10px;
  .detail__card {
    width: 100%;
    background: #ffffff;
    border-radius: 8px;
    padding: 10px 12px;
    margin-bottom: 10px;
    .detail__card-title {
      font-size: 16px;
      font-weight: 500;
      color: #222222;
      line-height: 20px;
      margin-bottom: 11px;
    }
    .detail__card-row {
      display: flex;
      margin-bottom: 10px;
      &:last-of-type {
        margin-bottom: 0;
      }
      .row__label {
        width: 96px;
        flex-shrink: 0;
        font-size: 14px;
        color: #999999;
        line-height: 18px;
        margin-right: 34px;
      }
      .row__value {
        width: calc(100% - 130px);
        font-size: 14px;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
      }
    }
  }
  .amount__box {
    .amount__top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .amount__top-left {
        width: 100%;
        margin-bottom: 0.25rem;
        .amount__title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          color: #222222;
          line-height: 20px;
        }
        .amount__count {
          font-size: 36px;
          font-weight: bold;
          color: #222222;
          line-height: 42px;
          margin-top: 7px;
          word-break: break-word;
          span.unit {
            font-size: 16px;
            font-weight: bold;
            color: #222222;
            line-height: 24px;
            margin-left: 4px;
          }
        }
      }
      .amount__top-right {
        flex-shrink: 0;
        width: 76px;
        height: 28px;
        border-radius: 14px;
        border: 1px solid #3f84f3;
        line-height: 28px;
        text-align: center;
        font-size: 13px;
        color: #3f84f3;
      }
    }
    .amount__bottom {
      border-top: 1px #eeeeee solid;
      padding-top: 13px;
      display: flex;
      justify-content: space-between;
      .amount__bottom-left {
        width: 100%;
        font-size: 14px;
        font-weight: 400;
        color: #999999;
        line-height: 18px;
        .left__row {
          width: 100%;
          display: flex;
          margin-bottom: 10px;
          justify-content: space-between;
          align-items: center;
          .status {
            white-space: nowrap;
          }
          .row__label {
            margin-right: 24px;
            flex-shrink: 0;
          }
          .row__value {
            word-break: break-all;
          }
          &:last-of-type {
            margin-bottom: 0;
          }
        }
      }
      .amount__bottom-right {
        font-size: 14px;
        color: #222222;
        line-height: 18px;
        text-align: right;
        max-width: 100px;
        flex-shrink: 0;
        .status {
          margin-bottom: 10px;
          &.sk {
            color: #faa64e;
          }
          &:last-of-type {
            margin-bottom: 0;
          }
        }
      }
    }
  }
  .contract__tool {
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 40px;
    background: #ffffff;
    .tool__btn {
      height: 28px;
      border-radius: 14px;
      border: 1px solid #3f84f3;
      padding: 0 12px;
      line-height: 28px;
      font-size: 13px;
      color: #3f84f3;
      margin-right: 4px;
      &:last-of-type {
        margin-right: 24px;
      }
    }
  }
}
</style>
<style lang="scss">
.van-popover--light.tips__popover {
  width: 50%;
}
.tips__box-popover {
  font-size: 14px;
  color: #222222;
  padding: 10px;
}
</style>
